import {
	Controller,
	Get,
	Post,
	Body,
	Patch,
	Param,
	Delete,
	UseGuards,
	Request,
} from "@nestjs/common";
import { AddressService } from "./address.service";
import { CreateAddressDto } from "./dto/create-address.dto";
import { UpdateAddressDto } from "./dto/update-address.dto";
import { JwtAuthGuard } from "../auth/guards/jwt-auth.guard";

@Controller("addresses")
@UseGuards(JwtAuthGuard)
export class AddressController {
	constructor(private readonly addressService: AddressService) {}

	@Post()
	async create(@Body() createAddressDto: CreateAddressDto, @Request() req) {
		try {
			// 确保地址属于当前用户
			createAddressDto.userId = req.user.id;
			const address = await this.addressService.create(createAddressDto);
			return {
				code: 200,
				data: address,
				message: "地址创建成功",
			};
		} catch (error) {
			return {
				code: error.status || 500,
				message: error.message || "创建地址失败",
			};
		}
	}

	@Get()
	async findAll(@Request() req) {
		try {
			const addresses = await this.addressService.findAll(req.user.id);
			return {
				code: 200,
				data: addresses,
				message: "获取地址列表成功",
			};
		} catch (error) {
			return {
				code: error.status || 500,
				message: error.message || "获取地址列表失败",
			};
		}
	}

	@Get(":id")
	async findOne(@Param("id") id: string, @Request() req) {
		try {
			const address = await this.addressService.findOne(+id, req.user.id);
			return {
				code: 200,
				data: address,
				message: "获取地址详情成功",
			};
		} catch (error) {
			return {
				code: error.status || 500,
				message: error.message || "获取地址详情失败",
			};
		}
	}

	@Patch(":id")
	async update(
		@Param("id") id: string,
		@Body() updateAddressDto: UpdateAddressDto,
		@Request() req
	) {
		try {
			const address = await this.addressService.update(
				+id,
				updateAddressDto,
				req.user.id
			);
			return {
				code: 200,
				data: address,
				message: "地址更新成功",
			};
		} catch (error) {
			return {
				code: error.status || 500,
				message: error.message || "更新地址失败",
			};
		}
	}

	@Delete(":id")
	async remove(@Param("id") id: string, @Request() req) {
		try {
			await this.addressService.remove(+id, req.user.id);
			return {
				code: 200,
				message: "地址删除成功",
			};
		} catch (error) {
			return {
				code: error.status || 500,
				message: error.message || "删除地址失败",
			};
		}
	}

	@Patch("default/:id")
	async setDefault(@Param("id") id: string, @Request() req) {
		try {
			const address = await this.addressService.setDefault(+id, req.user.id);
			return {
				code: 200,
				data: address,
				message: "设置默认地址成功",
			};
		} catch (error) {
			return {
				code: error.status || 500,
				message: error.message || "设置默认地址失败",
			};
		}
	}
}
